package com.qhhc.controller;

import com.qhhc.dto.CarAppointmentDto;
import com.qhhc.dtomapper.CarAppointmentMapperDto;
import com.qhhc.entity.CarAppointment;
import com.qhhc.entity.User;
import com.qhhc.enums.Status;
import com.qhhc.service.ICarAppointmentService;
import com.qhhc.service.UserService;
import com.qhhc.vo.CarAppointmentVo;
import com.qhhc.vo.GuestAppointmentVo;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@CrossOrigin
public class CarAppointmentController {

    @Autowired
    private ICarAppointmentService carAppointmentService;
    
    @Autowired
    private UserService userService;

    /**
     * 获取所有预约记录
     */
    @GetMapping("/api/appointments")
    public List<CarAppointmentDto> getAllAppointments() {

        List<CarAppointment> allAppointments = carAppointmentService.getAllAppointments();

        List<CarAppointmentDto> allAppointmentsDtoList = allAppointments.stream()
                .map(CarAppointmentMapperDto.INSTANCE::toDto)
                .collect(Collectors.toList());

        return allAppointmentsDtoList;
    }

    /**
     * 根据ID获取预约记录
     */
    @GetMapping("/api/appointments/{id}")
    public CarAppointmentDto getAppointmentById(@PathVariable Long id) {

        CarAppointment appointmentById = carAppointmentService.getAppointmentById(id);
        CarAppointmentDto appointmentDto = CarAppointmentMapperDto.INSTANCE.toDto(appointmentById);

        return appointmentDto;
    }

    /**
     * 根据用户ID获取预约记录
     */
    @GetMapping("/api/appointments/user/{userId}")
    public List<CarAppointmentDto> getAppointmentsByUserId(@PathVariable Long userId) {

        List<CarAppointment> appointmentsByUserId = carAppointmentService.getAppointmentsByUserId(userId);

        List<CarAppointmentDto> allAppointmentsDtoList = appointmentsByUserId.stream()
                .map(CarAppointmentMapperDto.INSTANCE::toDto)
                .collect(Collectors.toList());

        return allAppointmentsDtoList;
    }

    /**
     * 根据车辆ID获取预约记录
     */
    @GetMapping("/api/appointments/car/{carId}")
    public List<CarAppointmentDto> getAppointmentsByCarId(@PathVariable Long carId) {
        List<CarAppointment> appointmentsByCarId = carAppointmentService.getAppointmentsByCarId(carId);
        for (CarAppointment carAppointment : appointmentsByCarId) {
            System.out.println(carAppointment);
        }
        List<CarAppointmentDto> allAppointmentsDtoList = appointmentsByCarId.stream()
                .map(CarAppointmentMapperDto.INSTANCE::toDto)
                .collect(Collectors.toList());
        return allAppointmentsDtoList;
    }

    /**
     * 根据经销商ID获取预约记录
     */
    @GetMapping("/api/appointments/dealer/{dealerId}")
    public List<CarAppointmentDto> getAppointmentsByDealerId(@PathVariable Long dealerId) {
        List<CarAppointment> appointmentsByDealerId = carAppointmentService.getAppointmentsByDealerId(dealerId);

        List<CarAppointmentDto> allAppointmentsDtoList = appointmentsByDealerId.stream()
                .map(CarAppointmentMapperDto.INSTANCE::toDto)
                .collect(Collectors.toList());

        return allAppointmentsDtoList;
    }

    /**
     * 根据状态获取预约记录
     */
    @GetMapping("/api/appointments/status/{status}")
    public List<CarAppointmentDto> getAppointmentsByStatus(@PathVariable String status) {
        List<CarAppointment> appointmentsByStatus = carAppointmentService.getAppointmentsByStatus(status);
        List<CarAppointmentDto> allAppointmentsDtoList = appointmentsByStatus.stream()
                .map(CarAppointmentMapperDto.INSTANCE::toDto)
                .collect(Collectors.toList());
        return allAppointmentsDtoList;
    }

    /**
     * 条件查询预约记录
     */
    @PostMapping("/api/appointments/search")
    public List<CarAppointmentDto> searchAppointments(@RequestBody Map<String, Object> params) {
        List<CarAppointment> carAppointments = carAppointmentService.searchAppointments(params);
        List<CarAppointmentDto> allAppointmentsDtoList = carAppointments.stream()
                .map(CarAppointmentMapperDto.INSTANCE::toDto)
                .collect(Collectors.toList());
        return allAppointmentsDtoList;
    }

    /**
     * 添加预约记录
     */
    @PostMapping("/api/appointments")
    public Map<String, Object> addAppointment(@RequestBody CarAppointmentVo appointmentVo) {
        Map<String, Object> result = new HashMap<>();
        CarAppointment appointment = CarAppointmentMapperDto.INSTANCE.toEntity(appointmentVo);
//        System.out.println(appointment);

        int rows = carAppointmentService.addAppointment(appointment);

        if (rows > 0) {
            result.put("success", true);
            result.put("message", "添加成功");
            result.put("data", appointment);
        } else {
            result.put("success", false);
            result.put("message", "添加失败");
        }
        return result;
    }

    /**
     * 更新预约记录
     */
    @PutMapping("/api/appointments")
    public Map<String, Object> updateAppointment(@RequestBody CarAppointmentVo appointmentVo) {
        Map<String, Object> result = new HashMap<>();
        CarAppointment appointment = CarAppointmentMapperDto.INSTANCE.toEntity(appointmentVo);
        int rows = carAppointmentService.updateAppointment(appointment);
        if (rows > 0) {
            result.put("success", true);
            result.put("message", "更新成功");
        } else {
            result.put("success", false);
            result.put("message", "更新失败");
        }
        return result;
    }

    /**
     * 更新预约状态
     */
    @PutMapping("/api/appointments/{id}/status/{status}")
    public Map<String, Object> updateAppointmentStatus(@PathVariable Long id, @PathVariable String status) {
        Map<String, Object> result = new HashMap<>();
        status = Status.fromDescription(status).getValue();
        int rows = carAppointmentService.updateAppointmentStatus(id, status);
        if (rows > 0) {
            result.put("success", true);
            result.put("message", "状态更新成功");
        } else {
            result.put("success", false);
            result.put("message", "状态更新失败");
        }
        return result;
    }

    /**
     * 删除预约记录
     */
    @DeleteMapping("/api/appointments/{id}")
    public Map<String, Object> deleteAppointment(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        int rows = carAppointmentService.deleteAppointment(id);
        if (rows > 0) {
            result.put("success", true);
            result.put("message", "删除成功");
        } else {
            result.put("success", false);
            result.put("message", "删除失败");
        }
        return result;
    }

    /**
     * 根据车辆ID删除预约记录
     */
    @DeleteMapping("/api/appointments/car/{carId}")
    public Map<String, Object> deleteAppointmentsByCarId(@PathVariable Long carId) {
        Map<String, Object> result = new HashMap<>();
        int rows = carAppointmentService.deleteAppointmentsByCarId(carId);
        result.put("success", true);
        result.put("message", "删除成功");
        result.put("count", rows);
        return result;
    }

    /**
     * 为游客创建临时用户并添加预约
     */
    @PostMapping("/api/users/guest-appointment")
    public Map<String, Object> createGuestUserAndAppointment(@RequestBody GuestAppointmentVo guestAppointmentVo, 
                                                             HttpServletRequest request) {
        System.out.println("创建临时用户，接收到的数据: " + guestAppointmentVo);
        Map<String, Object> result = new HashMap<>();
        
        // 检查必填参数
        if (guestAppointmentVo == null) {
            result.put("success", false);
            result.put("message", "请求数据为空");
            return result;
        }
        
        if (guestAppointmentVo.getName() == null || guestAppointmentVo.getName().trim().isEmpty()) {
            result.put("success", false);
            result.put("message", "用户姓名不能为空");
            return result;
        }
        
        if (guestAppointmentVo.getPhone() == null || guestAppointmentVo.getPhone().trim().isEmpty()) {
            result.put("success", false);
            result.put("message", "手机号不能为空");
            return result;
        }
        
        if (guestAppointmentVo.getCarId() == null) {
            result.put("success", false);
            result.put("message", "车辆ID不能为空");
            return result;
        }
        
        if (guestAppointmentVo.getDealerId() == null) {
            result.put("success", false);
            result.put("message", "经销商ID不能为空");
            return result;
        }
        
        if (guestAppointmentVo.getAppointmentTime() == null) {
            result.put("success", false);
            result.put("message", "预约时间不能为空");
            return result;
        }
        
        try {
            // 打印详细的请求信息
            System.out.println("姓名: " + guestAppointmentVo.getName());
            System.out.println("手机号: " + guestAppointmentVo.getPhone());
            System.out.println("车辆ID: " + guestAppointmentVo.getCarId());
            System.out.println("经销商ID: " + guestAppointmentVo.getDealerId());
            System.out.println("预约时间: " + guestAppointmentVo.getAppointmentTime());
            System.out.println("备注: " + guestAppointmentVo.getNote());
            
            // 获取客户端IP地址
            String ipAddress = getClientIp(request);
            System.out.println("客户端IP: " + ipAddress);
            
            // 生成临时用户名和密码（IP + 时间戳）
            String timestamp = String.valueOf(System.currentTimeMillis());
            String tempUsername = "guest_" + ipAddress.replace(".", "_") + "_" + timestamp;
            String tempPassword = ipAddress + timestamp; // 实际应用中应该加密
            
            // 创建临时用户
            User newUser = new User();
            newUser.setUsername(tempUsername);
            newUser.setPassword(tempPassword);
            newUser.setNickname(guestAppointmentVo.getName());
            newUser.setPhone(guestAppointmentVo.getPhone());
            newUser.setUserType("03"); // 设置为普通用户
            newUser.setStatus("0"); // 设置为正常状态
            
            // 保存临时用户
            int userRows = userService.insertUser(newUser);
            
            if (userRows > 0 && newUser.getUserId() != null) {
                // 创建预约信息
                CarAppointment appointment = new CarAppointment();
                appointment.setUserId(newUser.getUserId());
                appointment.setCarId(guestAppointmentVo.getCarId());
                appointment.setDealerId(guestAppointmentVo.getDealerId());
                appointment.setAppointmentTime(guestAppointmentVo.getAppointmentTime());
                appointment.setStatus("0"); // 设置为待确认状态 (0: pending)
                appointment.setNote(guestAppointmentVo.getNote());
                
                // 保存预约信息
                int appointmentRows = carAppointmentService.addAppointment(appointment);
                
                if (appointmentRows > 0) {
                    result.put("success", true);
                    result.put("message", "预约成功");
                    result.put("userId", newUser.getUserId());
                    result.put("appointmentId", appointment.getId());
                } else {
                    // 如果预约失败，删除之前创建的用户
                    userService.deleteUser(newUser.getUserId());
                    result.put("success", false);
                    result.put("message", "预约失败");
                }
            } else {
                result.put("success", false);
                result.put("message", "创建临时用户失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "系统错误: " + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 获取客户端真实IP地址
     */
    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        
        // 如果是多级代理，取第一个IP地址
        if (ip != null && ip.contains(",")) {
            ip = ip.substring(0, ip.indexOf(",")).trim();
        }
        
        return ip == null ? "127.0.0.1" : ip;
    }
} 